const Router = require('koa-router');
const users = require('../models/users');
const { generateToken } = require('../middleware/auth');
const router = new Router();
router.prefix('/api/users');

// 登录路由
router.post('/login', async (ctx) => {
  const { loginName, password } = ctx.request.body;
  const userResult = await users.validateUser(loginName, password);

  if (userResult.status === 0) {
    const token = generateToken(userResult.user);
    ctx.body = { status: 0, msg: '登录成功', token };
  } else {
    ctx.status = 401;
    ctx.body = { status: 12, msg: '登录失败' };
  }
});

router.post('/register', async (ctx) => {
  const { login_name, password } = ctx.request.body; // 确保从请求体中获取正确的字段
  console.log('收到的注册数据:', ctx.request.body); // 打印收到的数据

  const registerResult = await users.registerUser(login_name, password); // 调用注册函数

  if (registerResult.status === 0) {
    ctx.body = { status: 0, msg: '注册成功', userId: registerResult.userId };
  } else {
    ctx.status = 400; // 返回400错误
    ctx.body = { status: registerResult.status, msg: registerResult.msg };
  }
});



module.exports = router;

